package com.crowntit.infrastructure.adapter.port;

import com.crowntit.domain.trade.adapter.port.ITradePort;
import com.crowntit.domain.trade.model.entity.NotifyTaskEntity;
import com.crowntit.infrastructure.event.EventPublisher;
import com.crowntit.infrastructure.gateway.GroupBuyNotifyService;
import com.crowntit.infrastructure.redis.RedissonService;
import com.crowntit.types.enums.NotifyTaskHTTPEnumVO;
import com.crowntit.types.enums.NotifyTaskTypeEnumVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class TradePort implements ITradePort {

    @Resource
    private GroupBuyNotifyService notifyService;

    @Resource
    private RedissonService redissonService;

    @Resource
    private EventPublisher publisher;

    @Override
    public String groupBuyNotify(NotifyTaskEntity notifyTaskEntity) {
        // 分布式锁
        RLock lock = redissonService.getLock(notifyTaskEntity.lockKey());
        try {
            if (lock.tryLock(3, 0, TimeUnit.SECONDS)){
                try {
                    if (notifyTaskEntity.getNotifyType().equals(NotifyTaskTypeEnumVO.HTTP.getCode())){
                        if (StringUtils.isBlank(notifyTaskEntity.getNotifyUrl()) || "暂无".equals(notifyTaskEntity.getNotifyUrl())) {
                            return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                        }
                        return notifyService.groupBuyNotify(notifyTaskEntity.getNotifyUrl(), notifyTaskEntity.getParameterJson());
                    }

                    if (notifyTaskEntity.getNotifyType().equals(NotifyTaskTypeEnumVO.MQ.getCode())){
                        publisher.publish(notifyTaskEntity.getNotifyMq(), notifyTaskEntity.getParameterJson());
                        return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
                    }
                } finally {
                    if (lock.isLocked() && lock.isHeldByCurrentThread()){
                        lock.unlock();
                    }
                }
            }
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        } catch (Exception e){
            Thread.currentThread().interrupt();
            return NotifyTaskHTTPEnumVO.NULL.getCode();
        }
    }
}
